<?php 
namespace User\Controller;
/**
 * 用户设置
 * @author HuHaiqin
 *
 */
class SettingController extends CommonController{
	
	public function index(){
		$this->display();
	}
	
	/**
	 * 修改基础信息
	 */
	public function base_post(){
		
		if(IS_POST){
			$paramDel = array(
					'username',
					'password',
					'type',
					'role',
					'status',
					'level',
			);//去除不能被修改的字段
			
			for($i = 0;$i < count($paramDel);$i++){
				unset($_POST[$paramDel[$i]]);
			}
			
			$_POST['uid'] = $_SESSION['loginUser']['uid']; //加入uid
			$_POST['update_time'] = Date('Y-m-d H:i:s');
			
			$m = D('Users');
			$data = $m->create($_POST); // 过滤其他字段
			
			if($m->save($data)){
				//重新生成$_SESSION['loginUser']
				
				$user = $m->find($_SESSION['loginUser']);
				unset($user['password']);
				unset($user['create_time']);
				unset($user['update_time']);
				$_SESSION['loginUser'] = $user;
				
				D('UserLog')->_add($user['uid'],'update_base','修改基础信息'); //写入日志
				_apiReturn(1, L('success'));
			}else{
				_apiReturn(0, L('failed'));
			}
		}
		
		
	}
	
	/**
	 * @desc 修改头像
	 * @param string avater 必须 头像路径
	 * @param string uid 必须 用户id
	 */
	public function avatar(){
		$avater = I('avatar');
		$uid = I('uid') ? I('uid') : $_SESSION['loginUser']['uid'];
		if(!$uid) _apiReturn(0,'您还未登录，不能修改头像',$data,$url);
		if(!$avater) _apiReturn(0,'头像路径不能为空',$data,$url);
		$m = D('Users');
		$data['uid'] = $uid;
		$data['avater'] = $avater;
		$data['update_time'] = Date('Y-m-d H:i:s');
		$result = $m->save($data);
		if($result){
			$_SESSION['loginUser']['avater'] = $data['avater'];
			D('UserLog')->_add($uid,'update_avatar','修改头像'); //写入日志
			_apiReturn(1,L('success'),$result,$url);
		}else{
			_apiReturn(0,L('failed'),$result,$url);
		}
	}
	
	/**
	 * @desc 修改密码接口
	 * @param string pwd  必须  密码
	 * @param string oldpwd 必须 原密码
	 * @return json {json统一结构} {status:1或0,info:信息,data:返回的数据,url:重定向地址}
	 */
	public function resetpwd_post(){

		$pwd = I('pwd');
		$oldpwd = I('oldpwd');
		$repwd = I('repwd');
		if(!$oldpwd) _apiReturn(0, L('error_info_miss_oldpwd'));
		if(!$pwd) _apiReturn(0,L('error_info_miss_pwd'));
		if($repwd != $pwd) _apiReturn(0, L('error_info_repwd'));
		
		$m = D('Users');
		
		$data['uid'] = $_SESSION['loginUser']['uid'];
		$has = $m->where($data)->find();
		
		$salt = $has['salt'];
		
		$data['password'] = md5(md5($oldpwd).$salt);
		if($m->where($data)->find()){
			$data['password'] = md5(md5($pwd).$salt);
			$data['update_time'] = Date('Y-m-d H:i:s');
			if($m->save($data)){
				D('UserLog')->_add($data['uid'],'reset_pwd','重置密码'); //写入日志
				_apiReturn(1,L('password').' '.L('update').' '.L('success'));
			}else{
				_apiReturn(0,L('password').' '.L('update').' '.L('failed'));
			}
		}else{
			_apiReturn(0, L('error_info_oldpwd_error'),$m->_sql());
		}
		
		
	}
}
?>